<script lang="ts" setup>
import { ref, watch } from "vue";
import { CellGroup, Picker, Popup, Button, Divider, showSuccessToast } from "vant";
// import OrganizationCascader from "@/components/OrganizationCascader/index.vue";
// import { SelectTypeEnum } from "@/components/OrganizationCascader/constants";
import Upload from "@/components/Upload/index.vue";
import type { FileDataType } from "@/components/Upload/types";
import usePost from "@/hooks/usePost";
import useRouterHook from "@/hooks/useRouterHook";
const { routerReplace } = useRouterHook();

// 检验
const validator = (v: any) => {
	return /^(\d+)(\.\d{1,2})?$/.test(v.toString()); //只能输入两个小数
};

/** 申请新增 */
const { runAsync: insertSealApplyApi } = usePost("POST", "/mistake-api/api/seal/apply/insert");
const form = ref<Record<string, any>>({
	// departCode: "",
	// departName: "",
	handlerName: "",
	sealType: "",
	// companyCode: "",
	companyName: "",
	sealCount: "",
	sealAmount: "",
	applyReason: "",
	attachment: "",
	attachmentPath: "",
	imagePath: ""
});
const fileList = ref<FileDataType[]>([]);
const pictures = ref<FileDataType[]>([]);
const types = ref([]);

const selectList = ref([]);
const columns = ref([
	{ text: "公司公章", value: "公司公章" },
	{ text: "公司合同章", value: "公司合同章" },
	{ text: "公司法人章", value: "公司法人章" },
	{ text: "其他(请在申请事由里备注)", value: "其他(请在申请事由里备注)" }
]);

const showTypePop = () => {
	selectList.value = types.value;
	typeState.value = true;
};

const confirmTypePop = () => {
	types.value = selectList.value;
	form.value.sealType = types.value.join(",");
	typeState.value = false;
};

const popupState = ref(false);
const typeState = ref(false);

const companyList = ref([
	{ text: "恒达智控", value: "恒达智控" },
	{ text: "嬴之科", value: "嬴之科" },
	{ text: "深圳智控", value: "深圳智控" },
	{ text: "郑州智控", value: "郑州智控" }
]);

const pickerConfirm = ({ selectedOptions }: any) => {
	const { text } = selectedOptions[0];
	// form.value.companyCode = value;
	form.value.companyName = text;
	popupState.value = false;
};

// const departmentVisble = ref(false);

// const confirmDepart = (selectedIds: string[], selectOptions: any[]) => {
// 	console.log(selectedIds, selectOptions);
// 	form.value.departCode = selectedIds[0];
// 	form.value.departName = selectOptions[0].departName;
// };

const onSubmit = async () => {
	console.log(form);
	if (pictures.value.length) {
		form.value.imagePath = pictures.value.map(item => item.fileUrl).join(",");
	}
	form.value.sealCount = Number(form.value.sealCount);
	const { ok, data } = await insertSealApplyApi(form.value);
	if (ok) {
		showSuccessToast("提交成功");
		setTimeout(() => {
			routerReplace({
				path: "/approveList",
				query: {
					type: 0,
					menu: 1
				}
			});
		}, 1500);
	}
	console.log(data);
};

const getRules = (msg: string, isSelect?: boolean): any => {
	return [{ required: true, message: (isSelect ? "请选择" : "请填写") + msg, trigger: "onChange" }];
};

const joinFile = () => {
	let names = "";
	let paths = "";
	let list = fileList.value;
	for (let i = 0, len = list.length; i < len; i++) {
		let item = list[i];
		names += i < len - 1 ? item.fileName + "," : item.fileName;
		paths += i < len - 1 ? item.fileUrl + "," : item.fileUrl;
	}
	form.value.attachment = names;
	form.value.attachmentPath = paths;
};

watch(
	() => fileList.value,
	() => {
		joinFile();
	}
);
</script>

<template>
	<van-form class="stampApply" @submit="onSubmit" label-align="top">
		<CellGroup inset>
			<!-- <Field
				v-model="form.departName"
				label="部门"
				placeholder="请选择"
				is-link
				readonly
				label-align="top"
				required
				:rules="getRules('部门', true)"
				@click="departmentVisble = true"
			/> -->
			<van-field v-model="form.handlerName" :label="'经办人'" placeholder="请输入" :rules="getRules('经办人')" required />
			<van-field
				v-model="form.sealType"
				readonly
				is-link
				:label="'用印类别'"
				placeholder="可多选"
				:rules="getRules('用印类别', true)"
				required
				@click="showTypePop"
			/>
			<van-field
				v-model="form.companyName"
				readonly
				is-link
				label="印章所属公司"
				placeholder="请选择"
				required
				:rules="getRules('印章所属公司', true)"
				@click="popupState = true"
			/>
			<van-field
				v-model="form.sealCount"
				type="digit"
				:rules="getRules('用章数量')"
				label="用章数量(需加盖印章次数)"
				placeholder="请输入数字"
				required
			/>
			<van-field
				label-width="10em"
				v-model="form.sealAmount"
				type="number"
				label="合同金额(没有填0)"
				:rules="[{ validator, message: '请填写合同金额且最多两位小数' }]"
				required
			>
				<template #input>
					<div style="white-space: nowrap">
						<span class="mark">CINY-人民币元</span><Divider :style="{ color: '#333', borderColor: '#333' }" vertical />
					</div>
					<van-field v-model="form.sealAmount" placeholder="若申请公司合同章，请填写合同总金额" />
				</template>
			</van-field>
			<van-field
				v-model="form.applyReason"
				type="textarea"
				autosize
				rows="2"
				label="申请事由"
				placeholder="请输入"
				:rules="getRules('申请事由')"
				required
			/>
			<van-cell center title="图片">
				<template #label>
					<Upload ref="picturesRef" v-model="pictures" :max-size="50 * 1024 * 1024" :max-count="20" preview />
				</template>
			</van-cell>
			<van-cell center title="附件">
				<template #label>
					<Upload
						ref="attachmentRef"
						v-model="fileList"
						buttonType
						:max-size="500 * 1024 * 1024"
						:max-count="30"
						accept="*"
					></Upload>
				</template>
			</van-cell>
		</CellGroup>
		<div style="margin: 16px">
			<Button round block type="primary" native-type="submit"> 提交 </Button>
		</div>
		<Popup v-model:show="popupState" position="bottom">
			<Picker teleport="body" :columns="companyList" @cancel="popupState = false" @confirm="pickerConfirm" />
		</Popup>

		<Popup v-model:show="typeState" position="bottom">
			<div style="display: flex; justify-content: space-between; height: 44px; line-height: 44px">
				<Button style="border: none; color: #969799" @click="typeState = false" size="normal">取消</Button>
				<Button style="border: none; color: #6398fb" @click="confirmTypePop" size="normal">确认</Button>
			</div>
			<van-checkbox-group v-model="selectList">
				<van-cell v-for="(item, index) in columns" :key="index" :title="`${item.text}`">
					<template #right-icon>
						<van-checkbox :name="item.value" />
					</template>
				</van-cell>
			</van-checkbox-group>
		</Popup>
		<!-- <OrganizationCascader
			:modelValue="departmentVisble"
			@confirm="confirmDepart"
			:type="SelectTypeEnum.Org"
			:default-selected="form.departCode ? [form.departCode] : []"
		></OrganizationCascader> -->
	</van-form>
</template>

<style lang="less" scoped>
.stampApply {
	margin-top: 10px;
	margin-bottom: 10px;
}
::v-deep(.van-checkbox-group) {
	max-height: 40vh;
	overflow-y: auto;
}

::v-deep(.van-checkbox-group::-webkit-scrollbar) {
	display: none;
}
.mark {
	font-size: var(--van-field-error-message-font-size);
}
</style>
